package com.chinapost.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chinapost.dao.BaseDaoI;
import com.chinapost.po.Tkind;
import com.chinapost.service.KindServiceI;
import com.chinapost.vo.DataGrid;
import com.chinapost.vo.Kind;

@Service("kindService")
public class KindServiceImpl implements KindServiceI {
	
	private BaseDaoI<Tkind> kindDao;

	public BaseDaoI<Tkind> getKindDao() {
		return kindDao;
	}

	@Autowired
	public void setKindDao(BaseDaoI<Tkind> kindDao) {
		this.kindDao = kindDao;
	}

	@Override
	public void add(Kind kind) {
		Tkind t = new Tkind();
		BeanUtils.copyProperties(kind, t);
		kindDao.save(t);
	}

	@Override
	public void edit(Kind kind) {
		Tkind t = kindDao.get(Tkind.class,kind.getCid());
		t.setCname(kind.getCname());
	}

	@Override
	public void delete(Kind kind) {
		String hql = "delete Tkind t where t.cid =:id";
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("id", kind.getCid());
		kindDao.executeHql(hql,params);
	}

	@Override
	public DataGrid datagrid(Kind kind) {
		DataGrid dg = new DataGrid();
		dg.setRows(listRows(find(kind)));
		dg.setTotal(total());
		return dg;
	}

	private Long total() {
		String hql = "select count(*) from Tkind t where 1=1";
		return kindDao.count(hql);
	}

	private List<Tkind> find(Kind kind) {
		String hql = "from Tkind t where 1=1";
		if (kind.getOrder() != null && kind.getSort() != null) {
			hql += " order by " + kind.getSort() + " " + kind.getOrder();
		}
		return kindDao.find(hql, kind.getPage(), kind.getRows());
	}

	private List<Kind> listRows(List<Tkind> lt) {
		List<Kind> rows = new ArrayList<Kind>();
		if (lt != null && lt.size() > 0) {
			for (Tkind t : lt) {
				Kind sub = new Kind();
				BeanUtils.copyProperties(t, sub);
				rows.add(sub);
			}
		}
		return rows;
	}

	@Override
	public List<Kind> combobox() {
		List<Kind> rl = new ArrayList<Kind>();
		List<Tkind> l = kindDao.find("from Tkind");
		if (l != null && l.size() > 0) {
			for (Tkind t : l) {
				Kind r = new Kind();
				r.setCid(t.getCid());
				r.setCname(t.getCname());
				rl.add(r);
			}
		}
		return rl;
	}

}

